﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KDAcctAttach {

    public partial class FrmDetach : Form {

        public FrmDetach()
        {
            InitializeComponent();
        }

        private List<DBItemModel> _dbList;

        #region 窗口载入

        private void FrmDetach_Shown(object sender, EventArgs e)
        {
            _dbList = new List<DBItemModel>();
            bsDBList.DataSource = _dbList;
        }

        #endregion 窗口载入

        #region 获取数据库列表

        private void GetDBList()
        {
            try
            {
                _dbList.Clear();
                bsDBList.ResetBindings(false);
                var db = DB.Inst();
                var lst = db.Ado.SqlQuery<DBItemModel>("select name 'DBName',dbid 'DBId',cmptlevel 'CMPTLevel',version 'DBVersion',filename 'DBPath' from sysdatabases;");
                if (lst is null)
                    return;
                if (lst.Count < 1)
                    return;
                _dbList.AddRange(lst);
                // 查询文件列表
                _dbList.ForEach(curDB =>
                {
                    //db.Ado.ExecuteCommand($"use {curDB.DBName};");
                    curDB.Files = db.Ado.SqlQuery<DBFilesModel>($"SELECT fileid 'FileId',size 'FileSize',name 'FileName',filename 'FilePath' FROM [{curDB.DBName}].[dbo].[sysfiles];");
                });
                bsDBList.ResetBindings(false);
                dgvAcctList.AutoResizeColumns();
                if (dgvAcctList.SelectedRows.Count > 0)
                {
                    GetSelectedName(dgvAcctList.SelectedRows[0].Index);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetSelectedName(int idx)
        {
            string name = dgvAcctList.Rows[idx].Cells["dBNameDataGridViewTextBoxColumn"].Value.ToString();
            var db = _dbList.FirstOrDefault(p => p.DBName == name);
            if (db is null)
                bsFiles.DataSource = new List<DBFilesModel>();
            else
                bsFiles.DataSource = db.Files;
            dgvFiles.AutoResizeColumns();
        }

        #endregion 获取数据库列表

        #region 刷新按钮

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            GetDBList();
        }

        #endregion 刷新按钮

        #region 窗口变动

        private void FrmDetach_Resize(object sender, EventArgs e)
        {
            dgvAcctList.Height = (int)((Height - plQuery.Height) * 0.7);
        }

        #endregion 窗口变动

        #region 选择行

        private void DgvAcctList_SelectionChanged(object sender, EventArgs e)
        {
            int idx = -1;
            if (dgvAcctList.SelectedRows.Count > 0)
                idx = dgvAcctList.SelectedRows[0].Index;
            if (idx < 0)
            {
                bsFiles.DataSource = new List<DBFilesModel>();
                return;
            }
            GetSelectedName(idx);
        }

        #endregion 选择行

        #region 批量分离

        private void BtnDetach_Click(object sender, EventArgs e)
        {
            try
            {
                List<DBItemModel> detachList = GetSelectedDB();
                var db = DB.Inst();
                string errInfo = "";
                detachList.ForEach(dbs =>
                {
                    try
                    {
                        db.Ado.ExecuteCommand($"sp_detach_db @dbname='{dbs.DBName}';");
                    }
                    catch (Exception ex)
                    {
                        errInfo += $"数据库:{dbs.DBName},错误信息:{ex.Message}\r\n";
                    }
                });
                if(!string.IsNullOrEmpty(errInfo))
                    throw new Exception("未成功列表:\r\n" +errInfo);
                MessageBox.Show("完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private List<DBItemModel> GetSelectedDB()
        {
            List<DBItemModel> detachList = new List<DBItemModel>();
            for (int i = 0; i < dgvAcctList.Rows.Count; i++)
            {
                var row = dgvAcctList.Rows[i];
                if (Convert.ToBoolean(row.Cells["colCheck"].Value) == true)
                {
                    var itm = _dbList.FirstOrDefault(p => p.DBName == row.Cells["dBNameDataGridViewTextBoxColumn"].Value.ToString());
                    if (itm != null)
                        detachList.Add(itm);
                }
            }
            if (detachList.Count < 1)
                throw new Exception("没有选择数据库");
            return detachList;
        }

        #endregion 批量分离

        #region 备份文件

        private async void BtnSaveFiles_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog fd = new FolderBrowserDialog();
                if (fd.ShowDialog() != DialogResult.OK)
                    return;
                string dir = fd.SelectedPath;
                if (!dir.EndsWith(@"\"))
                    dir += @"\";
                List<DBItemModel> detachList = GetSelectedDB();
                string errInfo = "";
                void cText(string info)
                {
                    if (InvokeRequired)
                        Invoke(new MethodInvoker(() =>
                        {
                            lbInfo.Text = info;
                        }));
                    else
                        lbInfo.Text = info;
                }
                string curInfo = "";

                await Task.Run(() =>
                 {
                     detachList.ForEach(db =>
                     {
                         curInfo = $"正在处理数据库:{db.DBName}";
                         cText(curInfo);
                         db.Files.ForEach(file =>
                            {
                                FileInfo fi = new FileInfo(file.FilePath);
                                try
                                {
                                    File.Copy(file.FilePath, dir + fi.Name);
                                }
                                catch (Exception ex)
                                {
                                    errInfo += ex.Message;
                                }
                            });
                     });
                 });
                cText("");
                MessageBox.Show("完成" + Environment.NewLine + errInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion 备份文件
        #region 选择
        private void BtnSelectAll_Click(object sender, EventArgs e)
        {
            if (_dbList.Count < 1)
                return;
            _dbList.ForEach(db => db.Checked = true);
        }
        private void BtnReverse_Click(object sender, EventArgs e)
        {
            if (_dbList.Count < 1)
                return;
            _dbList.ForEach(db => db.Checked = !db.Checked);
        }

        private void BtnCancelAll_Click(object sender, EventArgs e)
        {
            if (_dbList.Count < 1)
                return;
            _dbList.ForEach(db => db.Checked = false);
        }
        #endregion

        
    }
}